﻿using System;
using System.Linq;
using Solution.BusinessObject;
using Solution.Controls;
using Solution.Core;

namespace Solution
{
    public partial class Albums : PageBase
    {
        private int _catId;

        protected void Page_Load(object sender, EventArgs e)
        {
            // if request
            if (Request["cat"] != null)
            {
                _catId = Convert.ToInt32(Request["cat"]);
            }

            if (_catId <= 0)
            {
                return;
            }

            var category = CommonBO.MasterEDM.Categories
                .FirstOrDefault(t => t.Id == _catId);

            if (category == null)
            {
                return;
            }
            
            //if master category
            if (Equals(category.Parent, null))
            {
                // get random album in master category
                var subCats = CommonBO.MasterEDM.Categories
                    .Where(t => t.Parent.Id == category.Id)
                    .OrderBy(t => t.Views).ToArray();

                rptSubCategory.Visible = true;
                rptSubCategory.DataSource = subCats;
                rptSubCategory.DataBind();

                var randomAlbum = subCats
                    .SelectMany(t => t.Contents)
                    .OrderBy(t => t.Views)
                    .FirstOrDefault();

                if (randomAlbum != null)
                {
                    var albumSlider = (AlbumSlider) this.LoadControl("Controls/AlbumSlider.ascx");
                    albumSlider.AlbumId = randomAlbum.Id;
                    this.phdRandomAlbum.Visible = true;
                    this.phdRandomAlbum.Controls.Add(albumSlider);
                }
            }
                // if sub-category
            else
            {
                // get all albums in category
                var albums = CommonBO.MasterEDM.Contents
                    .Where(t=>t.Category.Id == _catId)
                    .OrderBy(t=>t.DisplayOrder)
                    .ToList();

                this.rptAlbums.Visible = true;
                this.rptAlbums.DataSource = albums;
                this.rptAlbums.DataBind();
            }
        }
    }
}